﻿
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Drawing;
using System.Drawing.Drawing2D;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Speech.AudioFormat;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using WebSocketServer.Common;
using Microsoft.AspNetCore.Hosting;
namespace MyApp.WebApi.Controllers
{
    public class ToolsController : NoAuthApiControllerBase
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        private string cropPath = "";
        private string upLoad = "";
        public ToolsController(IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
            cropPath = Path.Combine(_webHostEnvironment.WebRootPath, "cutpicture");
            upLoad = Path.Combine(_webHostEnvironment.WebRootPath, "upload");
            if (!Directory.Exists(cropPath))
            {
                Directory.CreateDirectory(cropPath);
            }
            if (!Directory.Exists(upLoad))
            {
                Directory.CreateDirectory(upLoad);
            }
        }
        /// <summary>
        /// 获取文件的MD5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string GetMD5(string str)
        {
            byte[] buffer = Encoding.Default.GetBytes(str); //将字符串解析成字节数组，随便按照哪种解析格式都行

            MD5 md5 = MD5.Create();  //使用MD5这个抽象类的Creat()方法创建一个虚拟的MD5类的对象。

            byte[] bufferNew = md5.ComputeHash(buffer); //使用MD5实例的ComputerHash()方法处理字节数组。

            string strNew = null;

            for (int i = 0; i < bufferNew.Length; i++)
            {

                strNew += bufferNew[i].ToString("x2");  //对bufferNew字节数组中的每个元素进行十六进制转换然后拼接成strNew字符串

            }
            return strNew;
        }

        /// <summary>
        /// 传入获取语音Base64
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        [HttpGet]
        public CommonResult Text2Vocie(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return new CommonResult() { Result = false };
            }
            string fileName = GetMD5(text) + ".wav";
            string Dir = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "speeh");
            if (!Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            string filePath = Path.Combine(Dir, fileName);
            try
            {
                if (text.Length > 65535)
                {
                    return new CommonResult() { Result = false };
                }
                if (!System.IO.File.Exists(filePath))
                {
                    using (SpeechSynthesizer synth = new SpeechSynthesizer())
                    {
                        synth.SetOutputToWaveFile(filePath, new SpeechAudioFormatInfo(32000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
                        PromptBuilder builder = new PromptBuilder();
                        builder.AppendText(text);
                        synth.Speak(builder);
                    }
                }
            }
            catch (Exception e)
            {
                return new CommonResult() { Result = false, ErrMsg = e.Message };
            }

            FileStream stream = new FileStream(filePath, FileMode.Open);
            string base64Str = "";
            using (BinaryReader binReader = new BinaryReader(stream))
            {
                byte[] bytes = binReader.ReadBytes(Convert.ToInt32(stream.Length));
                base64Str = Convert.ToBase64String(bytes);
            }
            return new CommonResult() { Result = true, ReturnData = base64Str };
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Upload()
        {
            int w = 0;
            int h = 0;
            var file = Request.Form.Files["fu_UploadFile"];
            string ext = Path.GetExtension(file.FileName).ToLower();
            string newName = Guid.NewGuid().ToString()+ext;
            string filePath = Path.Combine(upLoad,newName);        
            using (System.Drawing.Image mybitmap = System.Drawing.Bitmap.FromStream(file.OpenReadStream()))
            {
                w = mybitmap.Width;
                h = mybitmap.Height;
                using (var bmp = new Bitmap(w, h, mybitmap.PixelFormat))
                {
                    bmp.SetResolution(mybitmap.HorizontalResolution, mybitmap.VerticalResolution);
                    using (Graphics Graphic = Graphics.FromImage(bmp))
                    {
                        Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                        Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        Graphic.Clear(System.Drawing.Color.White);
                        Graphic.DrawImage(mybitmap, new Rectangle(0, 0, w, h), 0, 0, w, h, GraphicsUnit.Pixel);
                        var ms = new MemoryStream();
                        bmp.Save(filePath);
                    }
                }
            }
            float size = 0;
            int marginleft = 0;
            int magintop = 0;
            int big = 0;
            int XW = 400;
            int returnw = 0;
            int returnh = 0;
            if (w >= h)
            {
                big = w;
                returnw = XW;
                size = ((float)w / XW);
                returnh = (int)(h / size);
                magintop = (int)((float)(400 - returnh) / 2);
            }
            else
            {
                big = h;
                returnh = XW;
                size = ((float)h / XW);
                returnw = (int)(w / size);
                marginleft = (int)((float)(400 - returnw) / 2);
            }
            //size = float.Parse(size.ToString());
            string returns = "{\"ml\":" + marginleft + ",\"mt\":" + magintop + ",\"big\":" + big + ",\"gw\":" + returnw + ",\"gh\":" + returnh + ",\"src\":\"" + newName + "\"}";
            return returns;
        }

        /// <summary>
        /// 图片截取
        /// </summary>
        /// <param name="crop"></param>
        [HttpPost]
        public void Crop([FromBody] CropModel crop)
        {
            float size = (float)crop.Big / crop.Small;
            string newName = Guid.NewGuid().ToString();

            string[] pathArr= crop.ImgSrc.Split('/',StringSplitOptions.RemoveEmptyEntries);
            string filename = _webHostEnvironment.WebRootPath;
            for (int i = 0; i < pathArr.Length; i++)
            {
                filename= Path.Combine(filename, pathArr[i]);
            }
            string savepath = Path.Combine(cropPath, newName + ".jpg");
            CropHelper.Crop(filename, savepath, crop.W, crop.H, crop.X, crop.Y, size);
        }
    }
}
